import React, { Component } from 'react';
import Simditor from 'simditor'
import $ from  'jquery'

import './index.scss'
import '../../../node_modules/simditor/styles/simditor.scss'

// 通用的富文本编辑器，依赖jQuery
class RichEditor extends Component {
	constructor(props) {
		super(props);
		this.state = {  };
	}

	componentDidMount() {
		this.loadEditor()
	}

	componentWillReceiveProps(nextProps) {
		if(this.props.defaultDetail !== nextProps.defaultDetail) {
			this.simditor.setValue(nextProps.defaultDetail)
		}
	}

	loadEditor() {
		let element = this.refs['textarea'];
		this.simditor = new Simditor({
			textarea: $(element),
			defaultValue: this.props.placeholder || '请输入内容',
			upload: {
				url: '/api/manage/product/richtext_img_upload.do',
				defaultImage: '',
				fileKey: 'upload_file',
			}
		})
		this.bindEditorEvent()
	}

	bindEditorEvent() {
		this.simditor.on('valuechanged', e => {
			this.props.onValueChange(this.simditor.getValue());
		})
	}

	render() {
		return (
			<div className="rich-editor">
				<textarea ref="textarea"></textarea>
			</div>
		);
	}
}

export default RichEditor;
